package cn.tsingyu.antsblog.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.tsingyu.antsblog.util.Uploader;

import com.jfinal.core.Controller;

public class UploadController extends Controller{
	public void index(){
		HttpServletRequest request = super.getRequest();
		HttpServletResponse response = super.getResponse();
		Uploader up = new Uploader(request);
	    up.setSavePath("file");
	    String[] fileType = {".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"};
	    up.setAllowFiles(fileType);
	    up.setMaxSize(10000); //单位KB
	    try {
			up.upload();

		    String callback = request.getParameter("callback");

		    String result = "{\"name\":\""+ up.getFileName() +"\", \"originalName\": \""+ up.getOriginalName() +"\", \"size\": "+ up.getSize() +", \"state\": \""+ up.getState() +"\", \"type\": \""+ up.getType() +"\", \"url\": \""+ up.getUrl() +"\"}";

		    result = result.replaceAll( "\\\\", "\\\\" );
		    setAttr("url", up.getUrl());
		    if( callback == null ){
		    	renderJson(result);
		    }else{
		        response.getWriter().print("<script>"+ callback +"(" + result + ")</script>");
		    }
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
